<template>
  <div>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="addFormRef"
      label-position="top"
    >
      <el-form-item label="供应商名称" prop="providerName">
        <el-input
          v-model="addForm.providerName"
          placeholder="请输入供应商名称"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="providerPhone">
        <el-input
          v-model="addForm.providerPhone"
          placeholder="请输入联系方式"
        />
      </el-form-item>
      <el-form-item label="供应商等级" prop="levelId">
        <el-select
          v-model="addForm.levelId"
          placeholder="请选择供应商等级"
          filterable
        >
          <el-option
            v-for="item in props.levelList"
            :key="item.id"
            :label="item.levelName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品类型" prop="categoryIds">
        <el-checkbox-group v-model="addForm.categoryIds" class="flex flex-wrap">
          <el-checkbox
            v-for="item in props.categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="所属区域" prop="provinceId">
        <el-select
          v-model="addForm.provinceId"
          placeholder="请选择省份"
          filterable
          @change="
            getCityList();
            handleInit(1);
          "
        >
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="cityId">
        <el-select
          v-model="addForm.cityId"
          :placeholder="addForm.provinceId ? '请选择城市' : '请先选择省份'"
          filterable
          @change="
            getAreaList();
            handleInit(2);
          "
        >
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="areaId">
        <el-select
          v-model="addForm.areaId"
          :placeholder="addForm.cityId ? '请选择区县' : '请先选择城市'"
          filterable
          @change="
            getStreetList();
            handleInit(3);
          "
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="streetId">
        <el-select
          v-model="addForm.streetId"
          :placeholder="addForm.areaId ? '请选择街道' : '请先选择区县'"
          filterable
        >
          <el-option
            v-for="item in streetList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="addForm.address" placeholder="请输入详细地址" />
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button @click="handleCancel(0)">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetProvince,
  GetCity,
  GetArea,
  GetStreet,
} from "../../../../../wailsjs/go/api/BaseApi";
import {
  CreateProviderToOptician,
  UpdateProviderToOptician,
} from "../../../../../wailsjs/go/api/GoodsApi";

onMounted(() => {
  getProvinceList();
  if (props.detailForm.id != 0) {
    addForm.value = props.detailForm || {};
    addForm.value.categoryIds = addForm.value.categoryIds
      .split(",")
      .map(Number);
    getCityList();
    getAreaList();
    getStreetList();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => ({}),
  },

  categoryList: {
    type: Array,
    default: () => [],
  },
  levelList: {
    type: Array,
    default: () => [],
  },
});

const addFormRef = ref(null);
const addForm = ref({
  providerName: "",
  providerPhone: "",
  provinceId: null,
  provinceName: "",
  cityId: null,
  cityName: "",
  areaId: null,
  areaName: "",
  streetId: null,
  streetName: "",
  longitude: "0", // 经度
  latitude: "0", // 纬度
  address: "", // 详细地址
  level: null, // 供应商等级
  levelId: null, // 供应商等级id
  categoryIds: [],
  type: 1,
});

const handleCancel = (val = 0) => {
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;
    let form = cloneDeep(addForm.value);
    let foundLevel = props.levelList.find((item) => item.id == form.levelId);
    if (foundLevel) {
      form.level = foundLevel.level;
      form.levelName = foundLevel.levelName;
    }
    form.provinceName = provinceList.value.find(
      (item) => item.id == form.provinceId
    )?.name;
    form.cityName = cityList.value.find((item) => item.id == form.cityId)?.name;
    form.areaName = areaList.value.find((item) => item.id == form.areaId)?.name;
    form.streetName = streetList.value.find(
      (item) => item.id == form.streetId
    )?.name;

    form.categoryIds = form.categoryIds.join(",");

    if (props.detailForm.id == 0) {
      handleApiResponse(() => CreateProviderToOptician(form)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("新增成功");
          handleCancel(1);
        }
        loading.value = false;
      });
    } else {
      handleApiResponse(() => UpdateProviderToOptician(form)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("编辑成功");
          handleCancel(1);
        }
        loading.value = false;
      });
    }
  });
};

const levelList = ref([]);

const rules = ref({
  providerName: [{ required: true, message: "请输入供应商名称" }],
  providerPhone: [
    { required: true, message: "请输入联系方式" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入联系方式"));
        } else if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的联系方式"));
        } else {
          callback();
        }
      },
    },
  ],
  provinceId: [{ required: true, message: "请选择所属省份" }],
  cityId: [{ required: true, message: "请选择所属城市" }],
  areaId: [{ required: true, message: "请选择所属区域" }],
  streetId: [{ required: true, message: "请选择所属街道" }],
  levelId: [{ required: true, message: "请选择供应商等级" }],
  categoryIds: [{ required: true, message: "请选择商品类型" }],
  longitude: [{ required: true, message: "请选择所属区域" }],
  latitude: [{ required: true, message: "请选择所属区域" }],
  detailAddress: [{ required: true, message: "请输入详细地址" }],
});

const handleInit = (type) => {
  if (type == 1) {
    addForm.value.cityId = null;
    addForm.value.areaId = null;
  } else if (type == 2) {
    addForm.value.areaId = null;
  } else if (type == 3) {
    addForm.value.streetId = null;
  }
  addForm.value.streetId = null;
};

const provinceList = ref([]);
const cityList = ref([]);
const areaList = ref([]);
const streetList = ref([]);

const getProvinceList = () => {
  handleApiResponse(() => GetProvince()).then((res) => {
    if (res.code == 0) {
      provinceList.value = res.data.list || [];
    }
  });
};
async function getCityList() {
  handleApiResponse(() => GetCity(addForm.value.provinceId)).then((res) => {
    if (res.code == 0) {
      cityList.value = res.data.list || [];
    }
  });
}
async function getAreaList() {
  handleApiResponse(() => GetArea(addForm.value.cityId)).then((res) => {
    if (res.code == 0) {
      areaList.value = res.data.list || [];
    }
  });
}
async function getStreetList() {
  handleApiResponse(() => GetStreet(addForm.value.areaId)).then((res) => {
    if (res.code == 0) {
      streetList.value = res.data.list || [];
    }
  });
}
</script>

<style scoped lang="scss">
</style>